import React from 'react'
import { Table,Icon,Modal,Popconfirm,Form,Input,Row,Col,DatePicker,Button,Message,Select} from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import api from '../../../api/advPhoneType';
import advApi from '../../../api/advRelease';
import familyApi from '../../../api/advFamilyLockRelease';
import EditForm from '../../Form/AdvPhoneType';
import {uuid} from "../../../utils";

const { RangePicker } = DatePicker;
import moment from 'moment';

import PanelBox from '../../../components/PanelBox';
import {jsonToTree} from '../../../utils/tools'

import '../../../style/antd-theme.less';

export default class TablePage extends React.Component {
  state = {
    userSession:'',
    data: [],
    pagination: {
      pageSize:20,
      pageNum:1,
    },
    loading: false, 
    rowRecord:'',
    areaList:[],
  };
  columns = [{
    title: '标题',
    dataIndex: 'title',
  },{
    title: '上级',
    dataIndex: 'parentName',
    width: '10%',
  },{
    title: '状态',
    dataIndex: 'examState',
    width: '10%',
    render:(text, record, index) =>  {
      switch(record.examState){
        case 1:
          return '待审核';
        case 2:
         return '通过';
        case 3:
         return '拒绝';
        case 0:
         return '临时';
        default:
          return '';
      }
    },
  },{
    title: '起止时间',
    dataIndex: 'endDate',
    width: '26%',
    render:(text, record, index) =>  {
     return <span>{record.startDate} ~ {record.endDate}</span>
    },
  },{
    title: '创建时间',
    dataIndex: 'createDate',
    width: '14%',
  }, {
    title: '操作',
    key: 'action',
    width: '15%',
    render: (text, record) => (
      <span>
        <a href="javascript:void(0)" onClick={this.edit.bind(this, record)}>详情</a>
        <span className="ant-divider" />
        <Popconfirm title="您是否要删除该记录?" onConfirm={this.delete.bind(this, record.id)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
        <span className="ant-divider" />
        { !record.parentId ?
        <a href="javascript:void(0)" onClick={this.addChild.bind(this, record)}>添加下级</a>
        : ''}
      </span>
    ),
  }];

  handleTableChange = (pagination, filters, sorter) => {
    pagination.pageNum=pagination.current;
    this.setState({pagination});
   
    this.fetch({...pagination});
  }
  fetch = (params) => {
    this.setState({ loading: true });
    api.get('/advPhoneType/getAll', { params}).then((data) => {
      const _data = data.data.list;
      const pagination = { ...this.state.pagination };
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: _data,
        pagination,
      });
    });
  }

  componentDidMount = () =>{
    let user =this.props.profile.user;
    this.setState({
      userSession:user
      });
    this.fetch({ ...this.state.pagination });
  }

  addChild = (record) => {
    if(this.resetFields)this.resetFields();
    this.setState({
      isOpenModal: true,
      clearForm: false,
      titleName: '添加下级',
      rowRecord:{parentId:record.id,showPosition:1,examState:1,parentName:record.title},
    });
  }
  add = () => {
    if(this.resetFields)this.resetFields();
    this.setState({
      isOpenModal: true,
      clearForm: false,
      titleName: '添加分类',
      rowRecord:false,
    });
  }
  edit = (record, event) => {
    if(this.resetFields)this.resetFields();
    Promise.all([this.getRowById(record.id)]).then(([record]) => {
      const _data = record;
      let timeDef="";
      if( record && record.startDate && record.endDate){
        timeDef=[moment(record.startDate , "YYYY-MM-DD HH:mm:ss"), moment(record.endDate, "YYYY-MM-DD HH:mm:ss")];
        _data.timeDef=timeDef;
      }

      if(record.photos){
        let photos=JSON.parse(record.photos);
        let pho=photos[0]
        let url=pho+"?process=image/resize,width_150,height_150";
        _data.photoUrl=url;
      }

     

      this.setState({
        isOpenModal: true,
        clearForm: false,
        titleName: '修改分类',
        rowRecord: _data 
      });
    });
    
  }

  getRowById = (id) => {
    return new Promise((resolve, reject) => {
      api.get('/adv/getPhoneTypeById', { id: id }).then((data) => {
        resolve(data.data);
      });
    });
  }

  delete = (id,event) => {
    api.delete('/advPhoneType/delete', {id:id}).then((data) => {
      const result= data.data;
     if(result.code == 0){
      Message.success('删除成功！');
      this.fetch({ ...this.state.pagination });
     }else{
      Message.error(result.message);
     }
    });
  }
  close = () => {
    this.setState({
      isOpenModal: false,
      clearForm: true,
    });
  }
  refeshData = () => {
    this.fetch({ ...this.state.pagination });
  }

  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
  }


  render() {
    
    return (
      <div>
        <SearchForm searchCostState={this.state} goSearch={this.handleTableChange} create={this.add}/>
        <PanelBox>
          <Table columns={this.columns}  dataSource={this.state.data}  pagination={this.state.pagination}
            loading={this.state.loading}  onChange={this.handleTableChange}  rowKey='id'
          />
        </PanelBox>
        <Modal
          title={this.state.titleName}
          visible={this.state.isOpenModal}
          onCancel={this.close}
          width={800}
          wrapClassName="vertical-center-modal"
          footer={null}
        >
          <EditForm userSession={this.state.userSession} rowRecord={this.state.rowRecord}  close={this.close} refeshData={this.refeshData} clearForm={this.state.clearForm}  callbackParent={this.initChildrenParams}/>
        </Modal>
      </div>
    );
  }
}

    class SearchsForm extends React.Component {
      // 开始搜索
      goSearch = (e) => {
        let params=this.props.form.getFieldsValue().search;
        let _this=this.props;
        params.pageSize=_this.searchCostState.pagination.pageSize;
        params.pageNum =1;
        params.current =1;
        _this.goSearch(params);
     
      }

      srearchStyle = {
        labelCol: { span: 8},
        wrapperCol: { span: 14 },
      };
     
      render() {
        const { getFieldDecorator } = this.props.form;
        const {create } = this.props;
        const formItemLayout = this.srearchStyle;
        const search = {
          name: "title",
        };
        return <Form onSubmit={this.goSearch} layout="inline" style={{marginBottom:'10px'}}>
          <FormItem {...formItemLayout} label="标题" style={{marginRight:0,marginBottom:'10px'}}>
            {getFieldDecorator('search.title')(
              <Input type="text" placeholder="搜索的标题"/>
            )}
          </FormItem>
          <FormItem>
            <Button type="primary" icon="search" htmlType="submit">搜索</Button>
          </FormItem> 
          <FormItem>
            <Button type="primary" icon="plus" onClick={create}>添加新分类</Button>
          </FormItem>
        </Form>
      }
    }
    const SearchForm = Form.create({})(SearchsForm);